#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using GameVuTru.ManagerScreens;
using GameVuTru.GameObject;
using GameVuTru.ResourceManager;
#endregion

namespace GameVuTru.Screens
{
    class GameplayScreen : GameScreen
    {
        #region Fields
        public static int life = 3;
        public static int Phao = 100;
        public static int numcoin = 0;
        public static int numScore = 0;
        ContentManager content;
        BackGround bg;
        Random random;
        Player pl;
        CreateLevel lv;
        public static List<ItemBonus> ListBonus;
        public static List<Bullet> ListBulletEnemy;
        int count = 0;
        float Timefinsih = 0;//thoi gian chuyen man khj chjen thang
        public static bool boomIsexplosioned = false;//bao hieu boom da no roi,su dung bien nay ben CLass boom nhe

        //quan ly luc chet roi song lai
        float TimeLife = 0;//tinh toan thoi gian song lai
        float TimeShoot = 0;//tinh toan thoi gian de no ban dan tu dong
        //vitri button
        Vector2 posboom = new Vector2(750, 0);
        Vector2 pospause = new Vector2(0, 0);

        //
        public static Vector2 PosSprite = new Vector2(380, 400);
        public static bool ContinueGame = false; //khi bang false se Resume duoc
        public static Player staticPlayer = new Player();//bjen nay luu lai player cuoi cung truoc khi nhan nut pause

        //tinh diem cong mang
       public  int diem = 0;

        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        /// //nhan 
        public GameplayScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
            EnabledGestures = GestureType.Tap |
                           GestureType.HorizontalDrag |
                           GestureType.Flick |
                           GestureType.Hold |
                           GestureType.VerticalDrag |
                           GestureType.FreeDrag;



            lv = new CreateLevel();
            ContinueGame = false;
        }
        //ham nay dung cho resume
        public GameplayScreen(Player plstatic, List<CObject> list, List<Bullet> bulletenemy, List<ItemBonus> bonus)
        {
            lv = new CreateLevel();
            ContinueGame = true;
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
            EnabledGestures = GestureType.Tap |
                           GestureType.HorizontalDrag |
                           GestureType.Flick |
                           GestureType.Hold |
                           GestureType.VerticalDrag |
                           GestureType.FreeDrag;
            this.pl = plstatic;
            CreateLevel.listenemy = list;
            ListBonus = bonus;
            ListBulletEnemy = bulletenemy;

        }


        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            //bg.LoadContent(content);
            //  pl.LoadContent(content);

            //  font = content.Load<SpriteFont>("Nguon/gamefont");
            Thread.Sleep(1000);
            ScreenManager.Game.ResetElapsedTime();

            bg = new BackGround();
            random = new Random();

            if (!ContinueGame)
            {
                pl = new Player();
                ListBonus = new List<ItemBonus>();
                ListBulletEnemy = new List<Bullet>();
            }
            diem = numScore;
        }


        public override void UnloadContent()
        {
            content.Unload();
        }


        #endregion

        #region Update and Draw
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            //sau  20k duoc cong 1 mang
            if (numScore - diem >= 20000)
            {
                diem = numScore;
                life++;
                ManagerSound.PlaySound(ReSouce.soundlifeUp);
            }

            //neu ban dan tu dong
            if (OptionsMenuScreen.autoshoot)
            {
                TimeShoot += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                if (TimeShoot >= 150 && pl.isvisible)
                {
                    TimeShoot = 0;
                    pl.Shoot();
                    ManagerSound.PlaySound(ReSouce.soundplayshoot);
                }
            }

            //neu an duoc 50 dong tien doi  1 phao
            if (numcoin >= 25)
            {
                Phao++;
                numcoin -= 25;
            }
            //neu het mang chuyen sang GameOver
            if (life <= 0)
            {
                //chuyen sang game over
                Timefinsih += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                if (Timefinsih >= 2000)
                {
                    Timefinsih = 0;
                    ScreenManager.RemoveScreen(this);
                    ScreenManager.AddScreen(new GameOver(), null);

                }
            }
            //neu phao no thi tat ca chet
            if (boomIsexplosioned)
            {
                foreach (Enemy item in CreateLevel.listenemy)
                {
                    item.heath -= 20;
                    boomIsexplosioned = false;
                }
                foreach (Bullet item in ListBulletEnemy)
                {
                    item.isvisible = false;
                }

            }
            //song lai sau khi chet
            if (!pl.isvisible)
            {
                TimeLife += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (TimeLife >= 2)//2 giay se song lai
                {
                    TimeLife = 0;
                    pl.isvisible = true;
                    pl.Isprotected = true;
                    //ve vi tri giua man hinh
                    pl.postion = new Vector2(380, 400);
                }

            }
            count = 0;
            RemoveObjectIsvisibleFalse();
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            if (IsActive)
            {
                bg.Update(gameTime);
                lv.Update(gameTime);
                pl.Update(gameTime, CreateLevel.listenemy);
                for (int i = 0; i < ListBonus.Count; i++)
                {
                    pl.UpdateCollion(ListBonus[i]);
                }

                //update va cham voi dan quan dich
                for (int i = 0; i < ListBulletEnemy.Count; i++)
                {
                    if (ListBulletEnemy[i].isvisible)
                    {
                        ListBulletEnemy[i].Update(gameTime);
                        pl.UpdateCollion(ListBulletEnemy[i]);
                    }

                }

            }
            //dem so luong con song, ko con thi da chiien thag va chuyen man
            for (int i = 0; i < CreateLevel.listenemy.Count; i++)
            {
                if (CreateLevel.listenemy[i].isvisible)
                {
                    count++;
                }
            }
            if (count == 0)
            {
                Timefinsih += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                if (Timefinsih >= 5000)
                {
                    Timefinsih = 0;
                    PosSprite = pl.postion;
                    ScreenManager.RemoveScreen(this);
                    ScreenManager.AddScreen(new WinScreen(), null);

                }

            }


        }

        public override void HandleInput(InputState input)
        {
            if (pl.isvisible)
            {
                foreach (GestureSample gesture in input.Gestures)
                {
                    switch (gesture.GestureType)
                    {
                        case GestureType.Tap:
                            //nhap vao btn Boom
                            Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y);
                            if (new Rectangle((int)(posboom.X), (int)(posboom.Y), ReSouce.btnBoom.Width, ReSouce.btnBoom.Height).Contains(tapLocation))
                            {

                                if (Phao >= 1)
                                {
                                    ManagerSound.PlaySound(ReSouce.soundboomExplosion);
                                    pl.checkboom = true;
                                    Phao--;
                                }
                            }
                            //nhap vao btn pause
                            else if (new Rectangle((int)(pospause.X), (int)(pospause.Y), ReSouce.btnPause.Width, ReSouce.btnPause.Height).Contains(tapLocation))
                            {
                                ContinueGame = true;
                                ScreenManager.RemoveScreen(this);
                                ScreenManager.AddScreen(new BackgroundScreen(), null);
                                ScreenManager.AddScreen(new MainMenuScreen(), null);
                            }
                            else
                            {
                                if (!OptionsMenuScreen.autoshoot)
                                {
                                    pl.Shoot();
                                    ManagerSound.PlaySound(ReSouce.soundplayshoot);
                                }

                            }
                            break;
                        default:
                            break;
                    }

                    if (gesture.GestureType == GestureType.VerticalDrag || gesture.GestureType == GestureType.HorizontalDrag || gesture.GestureType == GestureType.FreeDrag)
                    {
                        pl.postion += gesture.Delta;
                    }
                }

                base.HandleInput(input);
            }

        }

        public override void Draw(GameTime gameTime)
        {
            // This game has a blue background. Why? Because!
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.CornflowerBlue, 0, 0);

            // Our player and enemy are both actually just text strings.
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            spriteBatch.Begin();

            bg.Draw(spriteBatch);
            pl.Draw(spriteBatch);

            lv.Draw(spriteBatch);

            for (int i = 0; i < ListBulletEnemy.Count; i++)
            {
                if (ListBulletEnemy[i].isvisible)
                {
                    ListBulletEnemy[i].Draw(spriteBatch);
                }
            }
            spriteBatch.Draw(ReSouce.NenScore, new Vector2(-70, 440), Color.White);
            spriteBatch.Draw(ReSouce.NenScore2, new Vector2(630, 440), Color.White);

            spriteBatch.DrawString(ScreenManager.Font, "" + life, new Vector2(30, 455), Color.White, 0f, Vector2.Zero, 0.5f, SpriteEffects.None, 0f);
            spriteBatch.DrawString(ScreenManager.Font, "" + Phao, new Vector2(67, 455), Color.White, 0f, Vector2.Zero, 0.5f, SpriteEffects.None, 0f);
            spriteBatch.DrawString(ScreenManager.Font, "" + Player.PowerBullet, new Vector2(107, 455), Color.White, 0f, Vector2.Zero, 0.5f, SpriteEffects.None, 0f);
            spriteBatch.DrawString(ScreenManager.Font, "" + numcoin, new Vector2(147, 455), Color.White, 0f, Vector2.Zero, 0.5f, SpriteEffects.None, 0f);
            spriteBatch.DrawString(ScreenManager.Font, "" + numScore, new Vector2(680, 445), Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0f);

            //ve button pause and boom
            spriteBatch.Draw(ReSouce.btnBoom, posboom, Color.White);
            spriteBatch.Draw(ReSouce.btnPause, pospause, Color.White);
            spriteBatch.End();

            // If the game is transitioning on or off, fade it out to black.
            if (TransitionPosition > 0)
                ScreenManager.FadeBackBufferToBlack(1f - TransitionAlpha);
        }
        public void RemoveObjectIsvisibleFalse()
        {
            for (int i = 0; i < ListBulletEnemy.Count; i++)
            {
                if (ListBulletEnemy[i].isvisible == false)
                {
                    ListBulletEnemy.RemoveAt(i);
                    i--;
                }
            }
            for (int i = 0; i < ListBonus.Count; i++)
            {
                if (ListBonus[i].isvisible == false)
                {
                    ListBonus.RemoveAt(i);
                    i--;
                }
            }
        }
        //phao no thi tat ca chet 

        public void allDie()
        {
            for (int i = 0; i < CreateLevel.listenemy.Count; i++)
            {
                CreateLevel.listenemy[i].isvisible = false;
            }
        }

        #endregion
    }
}
